package com.ojoin.ojoin.eb_spider.service.catchdata.suning;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.service.ISLDataCatchAtomStepService;
import com.ojoin.ojoin.eb_spider.service.SupplyPaymentService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.catchdata.SupplierSUNINGDataCatchServiceImpl;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

@Scope("prototype")
@Service
public class SUNINGSettlement implements
		ISLDataCatchAtomStepService<TbSlSupplyPayment> {
	@Autowired
	private SupplyPaymentService paymentService;
	private static Logger log = LoggerFactory
			.getLogger(SupplierSUNINGDataCatchServiceImpl.class);

	public WebDriverService webDriver;
	public TbSlPlatformUser platformUser;
	public String stime;
	public String etime;

	
	@Override
	public void get() {
		webDriver
				.get("http://scs.suning.com/sps/snsettlement/selectSNSettlement.action");

	}

	@Override
	public void sendKeys() {
		webDriver.sendKeys("id", "createTimeStart", stime);
		webDriver.sendKeys("id", "createTimeEnd", etime);

	}

	@Override
	public void submit() {
		webDriver
				.click("css",
						"#searchForm > table > tbody > tr:nth-child(4) > td:nth-child(3) > a ");
	}

	@Override
	public void run() {
		get();
		sendKeys();
		submit();

	}

	@Override
	public List<TbSlSupplyPayment> result() {
		List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();

		boolean flag = true;
		// 是否有下一页
		while (flag) {
			// findElement(attribute);
			WebElement table = webDriver.findElement("id", "gridTable");

			List<WebElement> trs = table.findElements(By.tagName("tr"));

			Iterator<WebElement> it = trs.iterator();
			while (it.hasNext()) {
				WebElement tr = it.next();
				if (webDriver.findElements(tr, "tagName", "td").size() > 2) {
					TbSlSupplyPayment payment = this
							.getTbSlSupplyPaymentByWebElement(tr);
					payments.add(payment);
				}else {
					return payments;
				}

			}

			flag = hasNextPage();
		}

		return payments;
	}

	public TbSlSupplyPayment getTbSlSupplyPaymentByWebElement(WebElement tr) {
		String settlementId = webDriver.getTextByJS(tr, "css",
				"td:nth-child(1)  div  a");

		String createDate = webDriver.getTextByJS(tr, "css",
				"td:nth-child(6) div");

		String type = webDriver.getTextByJS(tr, "css",
				"td:nth-child(4) div");
		
		String samount = webDriver.getTextByJS(tr, "css",
				"td:nth-child(5)  div");
	
		long amount = getLongAmount(samount);
 
		TbSlSupplyPayment payment = new TbSlSupplyPayment();

		payment.setPlatformAccountId(platformUser.getId());

		if (CommonUtils.isEmpty(settlementId)) {
			LogUtils.info(log, "settlementId is empty");
			settlementId = createDate + "_" + amount;
		}

		payment.setSettlementId(settlementId);
		payment.setCreateDate(createDate);
		payment.setSettlementState(TbSlSupplyPayment.WAITPAY);
		payment.setSettlementDate(createDate);
		payment.setAmount(amount);
        payment.setType(type);
		return payment;
	}

	public boolean hasNextPage() {

		WebElement ele = webDriver.findElement("css", "#pageFrm div .next");

		if (ele.getTagName().equals("span")) {
			return false;
		} else {
			webDriver.clickByJS(ele);
			return true;
		}
	}

	long getLongAmount(String samount) {
		long amount = 0;

		try {
			amount = NumberUtils.getLongAmount(samount);
		} catch (Exception e) {
			LogUtils.info(log, "%s to long is faile", samount);
		}
		return amount;
	}

	public void init(WebDriverService webDriver, TbSlPlatformUser platformUser,
			String stime, String etime) {
		this.webDriver = webDriver;

		this.platformUser = platformUser;
		this.stime = stime;
		this.etime = etime;

	}

	// SettlementTime 真实金额
	public void init(List<TbSlSupplyPayment> list) {

		Iterator<TbSlSupplyPayment> it = list.iterator();
		if (it.hasNext()) {
			TbSlSupplyPayment tb = it.next();
			String fiveDayPurchase = "http://scs.suning.com/sps/snsettlement/selectSNSettlement.action?statementCode="
					+ tb.getSettlementId();

			webDriver.get(fiveDayPurchase);

			WebElement web = webDriver.findElement("css",
					"#gridTable tbody  tr  td:nth-child(1)  div  a");

			String str = web.getAttribute("onclick");

			String[] strs = str.split("'");

			if (null != strs && strs.length > 1) {
				String DayPurchase = "http://scs.suning.com/sps/snsettlement/showSingPage.action?paysettlementid="
						+ strs[1];

				webDriver.checkAlert();
				webDriver.get(DayPurchase);

				WebElement webs = webDriver.findElement("css","body");

				String strtime = webs.getText().trim().replace("\n", "");
				Pattern ph4 = null;
				if (tb.getType().equals("经销")) {
					ph4 = Pattern
							.compile("结算期间:.{12}(.{10}).*本账期应付货款.{12,17}:(.{1,15})单位");

				} else {
					ph4 = Pattern
							.compile("结算期间:.{12,15}-(.{10}).*本期实付货款.{8,17}￥(.{1,15})");

				}

				Matcher mh4 = ph4.matcher(strtime);
				mh4.find();

				String time = mh4.group(1).replace("年", "-").replace("月", "-");
				String amont = mh4.group(2);

				tb.setSettlementDate(time);
				if (tb.getAmount() == 0) {
					tb.setAmount(getLongAmount(amont));
				}
			}

		}
	}

	@Override
	public void fiter(List<TbSlSupplyPayment> list,
			Map<String, TbSlSupplyPayment> map) {
		paymentService.removeSettlementCommon(list, map);
        
		init(list);

	}

}
